#include "voice.h"
#include "ui_voice.h"

voice::voice(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::voice)
{
    ui->setupUi(this);
    // int rowclick = 0;
    //加载数据库驱动
    database = new MyDatabase("mysong.db","song");
    //定义一个创建表格的SQL语句
    QString str = "create table IF NOT EXISTS mysong(\
            id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\
            songid varchar(255),\
            songname varchar(255),\
            artists varchar(255),\
            album varchar(255),\
            duration varchar(255)\
       )";
    //执行一个SQL语句
    database->execSql(str);

    ui->voiceSlider->setRange(0,100);
    ui->voiceSlider->setValue(50);  // 默认音量设置为50%

    pManager = new QNetworkAccessManager;//创建一个网络管理者
    //把管理者的finished信号和槽函数连接起来，该信号还携带了网址返回的数据
    connect(pManager,SIGNAL(finished(QNetworkReply *)),this,SLOT(finishedSlot(QNetworkReply *)));
    ui->tableWidget->setColumnCount(5);
    ui->tableWidget->setRowCount(20);
    //QHeaderView::Stretch属性是让表头自动拉伸到整个控件的宽度
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->setHorizontalHeaderLabels(QStringList()<<"歌名"<<"歌手"<<"专辑"<<"时长"<<"喜欢");

    player = new QMediaPlayer(this);//播放器
    audioOutput = new QAudioOutput;
    audioOutput->setVolume(0.5);
    player->setAudioOutput(audioOutput);//给播放器设置音频对象

    //把歌曲播放位置改变的信号和槽函数关联起来
    connect(player,SIGNAL(positionChanged(qint64)),this,SLOT(positionChangedSlot(qint64)));
    //把喜欢歌单的按钮改变的信号和槽函数关联起来
    connect(this,SIGNAL(mylove()),this,SLOT(mylovefinished()));

    currentIndex = 0;
}

voice::~voice()
{
    player->stop();
    delete ui;
}

void voice::parseJson(QByteArray &byteArr)
{
    //从JSON字符串构建一个JSON文档
    QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArr);
    //询问JSON文档是否一个对象
    if(jsonDoc.isObject() == true)
    {
        //把JSON文档转为JSON对象，这样就可以访问对象里面的关键字
        QJsonObject jsonObj = jsonDoc.object();
        //如果json对象是包含result关键字
        if(jsonObj.contains("result"))
        {
            //既然包含result，就可以获得result的值
            QJsonValue val = jsonObj.value("result");
            //问val是否是一个JSON对象
            if(val.isObject())
            {
                //把result的值转为JSON对象
                QJsonObject objR = val.toObject();
                //result对象是否包含songs关键字
                if(objR.contains("songs"))
                {
                    //得到songs的值
                    QJsonValue valS = objR.value("songs");
                    //判断songs的值是不是一个数组
                    if(valS.isArray())
                    {
                        //把song的值转为一个数组
                        QJsonArray arrSong = valS.toArray();
                        //遍历歌曲数组
                        for (int i = 0 ; i < arrSong.size() ; i++) {
                            musicInfo mi;//歌曲信息结构体
                            musicInfo data1;
                            //判断数组中下标为i的元素是否是一个对象
                            if(arrSong[i].isObject())
                            {
                                //把下标为i的元素转为对象
                                QJsonObject elmS = arrSong[i].toObject();
                                if(elmS.contains("id"))
                                {
                                    //获得id的值
                                    QJsonValue vid = elmS.value("id");
                                    //把值转为数字
                                    mi.id = vid.toDouble();//为了方式一个整数装不下ID，这里把ID转为double
                                    data1.id =vid.toDouble();
                                }
                                if(elmS.contains("name"))
                                {
                                    //获得name的值
                                    QJsonValue vName = elmS.value("name");
                                    mi.name = vName.toString();
                                    data1.name = vName.toString();
                                }
                                if(elmS.contains("duration"))
                                {
                                    //获得duration的值
                                    QJsonValue vDuration = elmS.value("duration");
                                    mi.duration = vDuration.toDouble();
                                    data1.duration = vDuration.toDouble();
                                }
                                if(elmS.contains( "artists" ))
                                {
                                    //获得duration的值
                                    QJsonValue vArtists = elmS.value("artists");
                                    if(vArtists.isArray())
                                    {
                                        QJsonArray arrArtists = vArtists.toArray();
                                        //遍历所有的歌手
                                        for (int j = 0 ; j < arrArtists.size() ; j++) {
                                            if(arrArtists[j].isObject())
                                            {
                                                //得到一个集体歌手的对象
                                                QJsonObject artistsObj = arrArtists[j].toObject();
                                                QJsonValue vArtistsName = artistsObj.value("name");
                                                mi.artists.push_back(vArtistsName.toString());//把歌手名加入到字符串列表中
                                                data1.artists.push_back(vArtistsName.toString());//把歌手名加入到字符串列表中
                                            }
                                        }
                                    }
                                }
                                if(elmS.contains("album"))//专辑
                                {
                                    //获得duration的值
                                    QJsonValue vAlbum = elmS.value("album");
                                    if(vAlbum.isObject())
                                    {
                                        QJsonObject vAlbumObj = vAlbum.toObject();
                                        QJsonValue vName = vAlbumObj.value("name");
                                        mi.album = vName.toString();
                                        data1.album = vName.toString();
                                    }
                                }

                            }

                            vMi.push_back(mi);//把一首歌的信息存入到数组中
                            vData.push_back(data1);//把一首歌的信息存入到数组中
                            // qDebug()<<mi.id<<" "<<mi.name<<" "<<mi.artists<<" "<<mi.album<<" "<<mi.duration/1000;

                            //同时把歌曲的信息加入到表格中，所以表格中的歌曲和数组容器中的歌曲顺序相同
                            //创建一个歌名的表格项
                            QTableWidgetItem *newItem = new QTableWidgetItem(mi.name);
                            ui->tableWidget->setItem(i, 0, newItem);
                            //歌手
                            QString artistsStr = "";
                            for (int k = 0 ; k < mi.artists.size() ; k++) {
                                artistsStr+=mi.artists[k];//把字符串列表中的每个名字加入到字符串中
                                artistsStr+="/";//用空格把名字隔开
                            }
                            newItem = new QTableWidgetItem(artistsStr);
                            ui->tableWidget->setItem(i, 1, newItem);
                            //专辑名
                            newItem = new QTableWidgetItem(mi.album);
                            ui->tableWidget->setItem(i, 2, newItem);
                            //时长
                            qlonglong sec = mi.duration/1000;//把毫秒转为秒
                            qlonglong min = sec/60;//算出分钟
                            sec = sec%60;//算出秒
                            newItem = new QTableWidgetItem(QString("%1:%2").arg(min).arg(sec,2, 10, QChar('0')));
                            ui->tableWidget->setItem(i, 3, newItem);

                            QPushButton *button = new QPushButton;
                            button->setStyleSheet("border-image: url(:/klove.png);");
                            button->setMaximumWidth(45);
                            button->setMaximumHeight(45);
                            ui->tableWidget->setCellWidget(i, 4, button);  // 在每一行的第三列添加按钮

                            QString str1 = QString("select * from mysong where songid = '%1' and songname = '%2'").arg(vData[i].id).arg(vData[i].name.replace("'","’"));
                            QSqlQuery *query = this->database->execSql(str1);
                            if(query && !query->next())
                            {
                                button->setStyleSheet("border-image: url(:/klove.png);");
                                ui->pushButton_7->setStyleSheet("border-image: url(:/klove.png);");
                            }
                            else
                            {
                                button->setStyleSheet("border-image: url(:/love.png);");
                                ui->pushButton_7->setStyleSheet("border-image: url(:/love.png);");
                            }

                            connect(button,&QPushButton::clicked,[this,button,i](){
                                QString dataArt = "";
                                for (int k = 0 ; k < vData[i].artists.size() ; k++) {
                                    dataArt+=vData[i].artists[k];//把字符串列表中的每个名字加入到字符串中
                                    dataArt+="/";//用空格把名字隔开
                                }
                                // dataArt.chop(1);
                                QString str1 = QString("select * from mysong where songid = '%1' and songname = '%2'").arg(vData[i].id).arg(vData[i].name.replace("'","’"));
                                QString str2 = QString("insert into mysong (songid,songname,artists,album,duration) values ('%1','%2','%3','%4','%5')")
                                                   .arg(vData[i].id).arg(vData[i].name.replace("'","’")).arg(dataArt.replace("'","’")).arg(vData[i].album.replace("'","’")).arg(vData[i].duration);
                                QString str3 = QString("DELETE FROM mysong WHERE songid = '%1'").arg(vData[i].id);
                                QSqlQuery *query = this->database->execSql(str1);
                                if(query && !query->next())
                                {
                                    button->setStyleSheet("border-image: url(:/love.png);");

                                    QString label1 = QString("%1").arg(vMi[i].name.replace("'","’"));
                                    QString label2 = QString("%1").arg(dataArt.replace("'","’"));
                                    QString label = label1 + " - " +  label2;
                                    if(label == ui->label->text())
                                    {
                                        ui->pushButton_7->setStyleSheet("border-image: url(:/love.png);");
                                    }
                                    // 存入数据库
                                    this->database->execSql(str2);
                                }
                                else
                                {

                                    QString label1 = QString("%1").arg(vMi[i].name.replace("'","’"));
                                    QString label2 = QString("%1").arg(dataArt.replace("'","’"));
                                    QString label = label1 +" - " + label2;
                                    if(label == ui->label->text())
                                    {
                                        ui->pushButton_7->setStyleSheet("border-image: url(:/klove.png);");
                                    }
                                    button->setStyleSheet("border-image: url(:/klove.png);");
                                    this->database->execSql(str3);
                                }
                            });
                        }
                    }
                }
            }
        }
    }
}

void voice::finishedSlot(QNetworkReply *reply)
{
    //首先通过应答对象(reply)获得网络状态码（HttpStatusCode），一般200代表成功，404代表找不到服务器
    QVariant code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    int ret = code.toInt();
    if(ret == 200)
    {
        qDebug()<<"请求网页成功";
        //读取所有的应答数据（网站返回的数据）
        QByteArray byteArr = reply->readAll();
        //        qDebug()<<byteArr.toStdString().c_str();
        parseJson(byteArr);//把网络发来的数据进行解析
    }
    else
    {
        qDebug()<<"请求网页失败，状态码为："<<ret;
    }
}

//搜索按键
void voice::on_pushButton_clicked()
{
    player->stop();

    //清空上一次搜索的歌曲
    vMi.clear();
    vData.clear();
    // vData.clear();
    // playList->clear();//清空播放列表
    QString info = ui->lineEdit->text();
    //构建了一个请求对象，里面包含了要请求的网址

    QNetworkRequest nr(QUrl(QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%1&type=1&offset=0&total=true&limit=20").arg(info)));

    //使用管理者的get函数(相当于是在浏览器的地址栏中敲了回车)发送请求，在完成请求后会产生一个finished信号，此时槽函数会获得结果,
    pManager->get(nr);
}

//双击表格播放歌曲
void voice::on_tableWidget_cellDoubleClicked(int row, int column)
{
    QString str1 = QString("select * from mysong where songid = '%1' and songname = '%2'").arg(vData[row].id).arg(vData[row].name.replace("'","’"));
    QSqlQuery *query = this->database->execSql(str1);
    if(query && !query->next())
    {
        ui->pushButton_7->setStyleSheet("border-image: url(:/klove.png);");
        // ui->pushButton_7->setStyleSheet("border-image: url(:/klove.png);");
    }
    else
    {
        ui->pushButton_7->setStyleSheet("border-image: url(:/love.png);");
        // ui->pushButton_7->setStyleSheet("border-image: url(:/love.png);");
    }
    if (row < 0 || row >= vMi.size()) {
        qDebug() << "Invalid row index:" << row;
        return;  // 避免继续执行，防止越界访问
    }
    currentIndex = row;
    //时长
    qlonglong secT = vMi[currentIndex].duration/1000;//把毫秒转为秒
    qlonglong minT = secT/60;//算出分钟
    secT = secT%60;//算出秒
    QString strT = QString("%1:%2").arg(minT).arg(secT,2, 10, QChar('0'));
    ui->label_total->setText(strT);
    QString url = QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(vMi[row].id);
    qDebug()<<url;
    player->setSource(QUrl(url));
    qDebug() << ui->voiceSlider->value();
    audioOutput->setVolume(ui->voiceSlider->value()/100.0);//设置音量
    qDebug()<<"歌曲的总时长为："<<vMi[row].duration;
    playing.id = vMi[row].id;
    playing.name = vMi[row].name;
    playing.artists = vMi[row].artists;
    playing.album = vMi[row].album;
    playing.duration = vMi[row].duration;

    QString artistsStr = "";
    for (int k = 0 ; k < vMi[row].artists.size() ; k++) {
        artistsStr+=vMi[row].artists[k];//把字符串列表中的每个名字加入到字符串中
        artistsStr+="/";//用"/"把名字隔开
    }
    QString S = vMi[row].name + " - " + artistsStr;

    ui->pushButton_4->setStyleSheet("border-image: url(:/bof.png);");
    ui->label->setText(S);

    // 开启 QScroller 滚动
    ui->label->adjustSize();
    // 开启定时器来滚动文本
    int labelWidth = ui->label->width();
    int textWidth = ui->label->fontMetrics().horizontalAdvance(S);  // 获取文本的宽度

        QTimer *timer = new QTimer(this);
        connect(timer, &QTimer::timeout, [=]() {
            int currentX = ui->label->x();
            if (currentX > -textWidth) {
                ui->label->move(currentX - 1, ui->label->y());  // 每次移动1个像素
            } else {
                ui->label->move(labelWidth, ui->label->y());  // 重置到右侧
            }
        });
        timer->start(70);  // 设置定时器每70毫秒调用一次

    ui->label->setText(S);
    player->play();
}

void voice::positionChangedSlot(qint64 position)
{
    //当前播放的进度/总时长 = 播放进度比
    qint64 precent = qint64(double(position)/vMi[currentIndex].duration*100);
    ui->horizontalSlider->setValue(precent);

    //时长
    qint64 sec1 = double(position)/1000;//把毫秒转为秒
    qint64 min1 = sec1/60;//算出分钟
    sec1 = sec1%60;//算出秒
    QString str = QString("%1:%2").arg(min1).arg(sec1,2, 10, QChar('0'));
    ui->label_real->setText(str);
}

void voice::on_horizontalSlider_sliderMoved(int position)
{
    //得到滑块的值
    float val = position;
    qint64 position1 = val/100*vMi[currentIndex].duration;
    player->setPosition(position1);
    qDebug()<<position1;
    qDebug()<<2;
}

void voice::on_horizontalSlider_sliderPressed()
{
    disconnect(player,SIGNAL(positionChanged(qint64)),this,SLOT(positionChangedSlot(qint64)));
    qDebug()<<1;
}

void voice::on_horizontalSlider_sliderReleased()
{
    connect(player,SIGNAL(positionChanged(qint64)),this,SLOT(positionChangedSlot(qint64)));
    qDebug()<<3;
}

void voice::on_voiceSlider_valueChanged(int value)
{
    float val = value/100.0;
    qDebug() << val;
    player->audioOutput()->setVolume(val);
}

void voice::on_pushButton_4_clicked()
{
    QMediaPlayer::PlaybackState playbackState = player->playbackState();
    if (playbackState == QMediaPlayer::PlayingState) {
        qDebug() << "播放器正在播放";
        ui->pushButton_4->setStyleSheet("border-image: url(:/zantin.png);");
        player->pause();
    } else if (playbackState == QMediaPlayer::PausedState) {
        qDebug() << "播放器已暂停";
        player->play();
        ui->pushButton_4->setStyleSheet("border-image: url(:/bof.png);");
    } else if (playbackState == QMediaPlayer::StoppedState) {
        qDebug() << "播放器已停止";
    }
}

//播放键旁边的喜欢按钮
void voice::on_pushButton_7_clicked()
{
    QString dataArt = "";
    for (int k = 0 ; k < playing.artists.size() ; k++) {
        dataArt+=playing.artists[k];//把字符串列表中的每个名字加入到字符串中
        dataArt+="/";//用空格把名字隔开
    }
    // dataArt.chop(1);
    QString str1 = QString("select * from mysong where songid = '%1' and songname = '%2'").arg(playing.id).arg(playing.name.replace("'","’"));
    QString str2 = QString("insert into mysong (songid,songname,artists,album,duration) values ('%1','%2','%3','%4','%5')")
                       .arg(playing.id).arg(playing.name.replace("'","’")).arg(dataArt.replace("'","’")).arg(playing.album.replace("'","’")).arg(playing.duration);
    QString str3 = QString("DELETE FROM mysong WHERE songid = '%1'").arg(playing.id);

    QSqlQuery * query = this->database->execSql(str1);
    QPushButton *button = new QPushButton;
    button->setMaximumWidth(45);
    button->setMaximumHeight(45);
    if(query->next()==false)
    {
        ui->pushButton_7->setStyleSheet("border-image: url(:/love.png);");
        button->setStyleSheet("border-image: url(:/love.png);");
        this->database->execSql(str2);
    }
    else
    {
        ui->pushButton_7->setStyleSheet("border-image: url(:/klove.png);");
        button->setStyleSheet("border-image: url(:/klove.png);");
        this->database->execSql(str3);
    }
    ui->tableWidget->setCellWidget(currentRow,4,button);
}

void voice::closeEvent(QCloseEvent *event)
{
    player->stop();
}


void voice::on_pushButton_3_clicked()
{
    int rowcount = 0;
    ui->tableWidget->clear();
    //QHeaderView::Stretch属性是让表头自动拉伸到整个控件的宽度
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->setHorizontalHeaderLabels(QStringList()<<"歌名"<<"歌手"<<"专辑"<<"时长"<<"喜欢");
    QSqlQuery *query1 = this->database->execSql("SELECT COUNT(*) FROM mysong");
    QSqlQuery *query2 = this->database->execSql("SELECT * FROM mysong");
    if(query1->next())
    {
        rowcount = query1->value(0).toInt();//获取行数
    }
    qDebug() << "1";
    ui->tableWidget->setColumnCount(5);
    ui->tableWidget->setRowCount(rowcount);
    for (int i = 0 ;query2->next() ; i++)
    {
        qDebug() << "1";
        QString name;//歌名
        QString artists;//歌手
        QString album;//专辑
        QString dura;//时长
        //歌名
        name = query2->value("songname").toString();
        QTableWidgetItem *newItem = new QTableWidgetItem(name);
        ui->tableWidget->setItem(i,0,newItem);

        //歌手
        artists = query2->value("artists").toString();
        newItem = new QTableWidgetItem(artists);
        ui->tableWidget->setItem(i,1,newItem);

        //专辑
        album = query2->value("album").toString();
        newItem = new QTableWidgetItem(album);
        ui->tableWidget->setItem(i,2,newItem);

        QString duration = query2->value("duration").toString();
        int num = std::stoi(duration.toStdString());
        qlonglong sec = num/1000;//把毫秒转为秒
        qlonglong min = sec/60;//算出分钟
        sec = sec%60;//算出秒
        dura = QString("%1:%2").arg(min).arg(sec,2, 10, QChar('0'));
        newItem = new QTableWidgetItem(dura);
        ui->tableWidget->setItem(i,3,newItem);

        STR lo ;
        lo.id = query2->value("songid").toString();
        lo.name = query2->value("songname").toString();
        lo.artists = query2->value("artists").toString();
        lo.album = query2->value("album").toString();
        lo.duration = query2->value("duration").toString();

        //按钮
        QPushButton *button = new QPushButton;
        button->setStyleSheet("border-image: url(:/love.png);");
        button->setMaximumWidth(45);
        button->setMaximumHeight(45);
        ui->tableWidget->setCellWidget(i, 4, button);  // 在每一行的第三列添加按钮

        connect(button,&QPushButton::clicked,[this,button,lo](){
            QString str1 = QString("select * from mysong where songid = '%1' and songname = '%2'").arg(lo.id).arg(lo.name);
            QString str3 = QString("DELETE FROM mysong WHERE songid = '%1'").arg(lo.id);
            QSqlQuery *query = this->database->execSql(str1);
            if(query->next())
            {
                button->setStyleSheet("border-image: url(:/klove.png);");
                this->database->execSql(str3);
            }
        });
    }
    emit mylove();
}


//播放下一首
void voice::on_pushButton_6_clicked()
{
    qDebug() << vMi.size();
    currentRow++;
    currentIndex = currentRow+1;
    int row = currentRow+1;
    //时长
    qlonglong secT = vMi[currentIndex].duration/1000;//把毫秒转为秒
    qlonglong minT = secT/60;//算出分钟
    secT = secT%60;//算出秒
    QString strT = QString("%1:%2").arg(minT).arg(secT,2, 10, QChar('0'));
    ui->label_total->setText(strT);
    QString url = QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(vMi[row].id);
    qDebug()<<url;
    player->setSource(QUrl(url));
    qDebug() << ui->voiceSlider->value();
    audioOutput->setVolume(ui->voiceSlider->value()/100.0);//设置音量
    qDebug()<<"歌曲的总时长为："<<vMi[row].duration;
    playing.id = vMi[row].id;
    playing.name = vMi[row].name;
    playing.artists = vMi[row].artists;
    playing.album = vMi[row].album;
    playing.duration = vMi[row].duration;

    QString artistsStr = "";
    for (int k = 0 ; k < vMi[row].artists.size() ; k++) {
        artistsStr+=vMi[row].artists[k];//把字符串列表中的每个名字加入到字符串中
        artistsStr+="/";//用"/"把名字隔开
    }
    QString S = vMi[row].name + " - " + artistsStr;

    ui->pushButton_4->setStyleSheet("border-image: url(:/bof.png);");
    ui->label->setText(S);
    // 开启 QScroller 滚动
    // QScroller::grabGesture(ui->label, QScroller::LeftMouseButtonGesture);
    ui->label->adjustSize();
    // 开启定时器来滚动文本
    int labelWidth = ui->label->width();
    int textWidth = ui->label->fontMetrics().horizontalAdvance(S);  // 获取文本的宽度

    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, [=]() {
        int currentX = ui->label->x();
        if (currentX > -textWidth) {
            ui->label->move(currentX - 1, ui->label->y());  // 每次移动1个像素
        } else {
            ui->label->move(labelWidth, ui->label->y());  // 重置到右侧
        }
    });
    timer->start(70);  // 设置定时器每70毫秒调用一次

    ui->label->setText(S);
    player->play();
}

//播放上一首
void voice::on_pushButton_5_clicked()
{
    currentRow--;
    currentIndex = currentRow-1;
    int row = currentRow-1;
    //时长
    qlonglong secT = vMi[currentIndex].duration/1000;//把毫秒转为秒
    qlonglong minT = secT/60;//算出分钟
    secT = secT%60;//算出秒
    QString strT = QString("%1:%2").arg(minT).arg(secT,2, 10, QChar('0'));
    ui->label_total->setText(strT);
    QString url = QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(vMi[row].id);
    qDebug()<<url;
    player->setSource(QUrl(url));
    qDebug() << ui->voiceSlider->value();
    audioOutput->setVolume(ui->voiceSlider->value()/100.0);//设置音量
    qDebug()<<"歌曲的总时长为："<<vMi[row].duration;
    playing.id = vMi[row].id;
    playing.name = vMi[row].name;
    playing.artists = vMi[row].artists;
    playing.album = vMi[row].album;
    playing.duration = vMi[row].duration;

    QString artistsStr = "";
    for (int k = 0 ; k < vMi[row].artists.size() ; k++) {
        artistsStr+=vMi[row].artists[k];//把字符串列表中的每个名字加入到字符串中
        artistsStr+="/";//用"/"把名字隔开
    }
    QString S = vMi[row].name + " - " + artistsStr;

    ui->pushButton_4->setStyleSheet("border-image: url(:/bof.png);");
    ui->label->setText(S);
    // 开启 QScroller 滚动
    // QScroller::grabGesture(ui->label, QScroller::LeftMouseButtonGesture);
    ui->label->adjustSize();
    // 开启定时器来滚动文本
    int labelWidth = ui->label->width();
    int textWidth = ui->label->fontMetrics().horizontalAdvance(S);  // 获取文本的宽度

    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, [=]() {
        int currentX = ui->label->x();
        if (currentX > -textWidth) {
            ui->label->move(currentX - 1, ui->label->y());  // 每次移动1个像素
        } else {
            ui->label->move(labelWidth, ui->label->y());  // 重置到右侧
        }
    });
    timer->start(70);  // 设置定时器每70毫秒调用一次

    ui->label->setText(S);
    player->play();

}

void voice::mylovefinished()
{
        int rowcount = 0;
     // && (!query2->value().isNull())
        QSqlQuery *query1 = this->database->execSql("SELECT COUNT(*) FROM mysong");
        QSqlQuery *query2 = this->database->execSql("SELECT * FROM mysong");
        if(query1->next())
        {
            rowcount = query1->value(0).toInt();//获取行数
        }
        qDebug() << rowcount;
        QVector<musicInfo> V;//存放搜索到的歌曲信息的数组容器
        // query2->next()   i < rowcount
        V.reserve(rowcount);
        if (query2->next()) {
            do {
                musicInfo lo;
                lo.id = query2->value("songid").toString().toLongLong();
                qDebug() << lo.id;
                lo.name = query2->value("songname").toString();
                qDebug() << lo.name;

                // 使用 split 方法按 '/' 分割字符串
                QString artists1 = query2->value("artists").toString();
                QStringList artistsList = artists1.split('/');
                if (!artistsList.isEmpty() && artistsList.last().isEmpty()) {
                    artistsList.removeLast();
                }
                lo.artists = artistsList;
                qDebug() << lo.artists;

                lo.album = query2->value("album").toString();
                qDebug() << lo.album;
                lo.duration = query2->value("duration").toLongLong();
                qDebug() << lo.duration;
                V.push_back(lo);
            } while (query2->next());  // 使用 next() 读取后续数据
        }
        vMi.clear();
        vMi.reserve(rowcount);
        vMi = V;

        vData.clear();
        vData.reserve(rowcount);
        vData = V;
}
